# -*- coding: UTF-8 -*-
"""
@Project : FastTortoiseDemo
@File    : .py
@IDE     : PyCharm
@Author  : xuan
@Date    : 2023/12/29 11:33
"""
from datetime import timedelta

from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordRequestForm
from Apps.user.user_schemas import UserCreateSchema, UserUpdateSchema, UserResponse, Token, UserData, UserLoginSchema
from Apps.user.user_services import UserService
from Apps.user.authentication import get_current_active_user, login_for_access_token
from Apps.user.user_models import User

router = APIRouter(
    prefix="/users",
    tags=["Users"],
    responses={404: {"description": "Not Found"}},
)


@router.post("/all", response_model=UserResponse, tags=["Users"])
async def all_users():
    """
    获取全部用户
    :return:
    """
    user = await UserService.get_all_users()
    return {"message": user} if user else {"message": "未找到用户"}


@router.get("/users/me/", response_model=UserData)
async def read_users_me(current_user: User = Depends(get_current_active_user)):
    return current_user


# 注册 User
@router.post("/register", tags=["Users"])
async def register(user_data: UserCreateSchema):
    """
    注册接口
    :param user:
    :return:
    """
    return await UserService.create_user(user_data)


@router.post("/token", tags=["Users"])
async def login(form_data: OAuth2PasswordRequestForm = Depends()) -> Token:
    return await login_for_access_token(form_data)


@router.post("/login", tags=['Users'])
async def login(request_data: UserLoginSchema) -> Token:
    return await login_for_access_token(request_data)


@router.post("/logout/{user_id}", tags=["Users"])
async def logout(user_id: int):
    """
    退出登录
    :param user_id:
    :return:
    """
    user = await UserService.logout_user(user_id)
    return {"message": user} if user else {"message": "退出失败"}


@router.post("/update_user", tags=["Users"])
async def update_user(user_id: int, updated_user: UserUpdateSchema):
    """
    更新用户
    :param user_id:
    :param updated_user:
    :return:
    """
    user = await UserService.update_user(user_id, updated_user)
    return {"message": user} if user else {"message": "更新失败"}


@router.post("/delete_user", tags=["Users"])
async def delete_user(user_id: int):
    """
    删除用户
    :param user_id:
    :return:
    """
    user = await UserService.delete_user(user_id)
    return {"message": user} if user else {"message": "删除失败"}
